﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B10.Models;
using B10.Helpers;
using Microsoft.Security.Application;

namespace B10.Controllers
{
    [HandleError]
    [Authorize]
    public class CommentController : Controller
    {

        IDatabaseRepository _db;

        public CommentController()
            : this(new DatabaseRepository())
        {
        }

        public CommentController(IDatabaseRepository db)
        {
            _db = db;
        }


        [HttpGet]
        [ChildActionOnly]
        public ActionResult Add()
        {
            Comment c = new Comment();
            return View("AddComment", c);
        }


        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Add(int id, FormCollection collection)
        {
            UserPage page = _db.GetPage(id);
            if (page == null || page.Status != PageStatus.Accepted || !page.AllowComments)
                return null;
            Comment comment = new Comment();
            if (UserHelper.UserId.HasValue)
                comment.ProfileId = UserHelper.UserId.Value;
            //comment.Author = User.Identity.Name;
            comment.Date = DateTime.Now;
            comment.UserPage = page;
            if (collection.AllKeys.Contains("Body"))
            {
                comment.Body = AntiXssHtmlHelper.GetSafeHtml(collection["Body"]);
            }
            if (collection.AllKeys.Contains("replyId"))
            {
                string replyId = collection["replyId"];
                int repId;
                if (!String.IsNullOrEmpty(replyId) && Int32.TryParse(replyId, out repId))
                {
                    Comment parent = _db.GetComment(repId);
                    if (parent != null && parent.Comment1 == null)
                        comment.Comment1 = parent;
                }
            }
            if (!ModelState.IsValid)
                return null;
            _db.Save();
            return View("Comment", comment);
        }

    }
}
